package com.xxx.user.controller;

import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;
import com.xxx.user.domain.User;
import com.xxx.user.query.UserQuery;
import com.xxx.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户类接口")
public class UserController {
    @Autowired
    private IUserService userService;

    @GetMapping
    @ApiOperation(value = "查询所有")
    public R<List<User>> finfAll(){
        List<User> list = userService.findAll();
        return R.ok(list);
    }
    @GetMapping("/{id}")
    @ApiOperation(value = "ID查询单个")
    public R<User> findOne(@PathVariable Long id) {
        User user = userService.findOne(id);
        return R.ok(user);
    }
    @PostMapping
    @ApiOperation(value = "分页查询")
    public PageInfo<User> findByPage(@RequestBody UserQuery userQuery) {
        List<User> byPage = userService.findByPage(userQuery);
        PageInfo<User> pageInfo = new PageInfo<>(byPage);
        return pageInfo;
    }

    @PutMapping
    @ApiOperation(value = "增加或者修改")
    public R<Void> updateOrInsert(@RequestBody User user){
        try {
            if (user.getId()!=null){
                userService.updateById(user);
            }else {
                userService.insert(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("用户名重复");
        }
        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除用户")
    public R<Void> delete(@PathVariable Long id){
        userService.deleteById(id);
        return R.ok();
    }


    @PatchMapping
    @ApiOperation(value = "批量删除用户")
    public R<Void> bathUsers(@RequestBody Long[] ids) {
        try {
            userService.bathUsers(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }
}
